package com.abaaba.project2.service.wx.wxserviceimpl;

import com.abaaba.project2.bean.*;
import com.abaaba.project2.bean.System;
import com.abaaba.project2.bean.bo.CartAddBo;
import com.abaaba.project2.bean.bo.CartUpdateBo;
import com.abaaba.project2.bean.bo.CheckedBo;
import com.abaaba.project2.bean.bo.wx.DeleteCartBo;
import com.abaaba.project2.bean.data.wx.CartCountInfo;
import com.abaaba.project2.bean.vo.wx.CheckInfoVo;
import com.abaaba.project2.bean.vo.wx.WxCartListVo;
import com.abaaba.project2.mapper.*;
import com.abaaba.project2.service.wx.WxCartService;
import com.abaaba.project2.util.UserIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class WxCartServiceImpl implements WxCartService {

    @Autowired
    CartMapper cartMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    SystemMapper systemMapper;
    @Autowired
    Coupon_UserMapper coupon_userMapper;

    @Override
    public Integer getGoodsNumInCart(Integer loginUserid) {

        CartExample cartExample =  new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(loginUserid)
                .andDeletedEqualTo(false);

        List<Cart> carts = cartMapper.selectByExample(cartExample);
        Integer sum = 0;
        for (Cart cart : carts) {

            sum += cart.getNumber();
        }

        return sum;
    }

    @Override
    public Integer addGoodsIntoCart(CartAddBo cartAddBo) {

        //先判断有没有这种类型的商品，如果有，则合并
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria2 = cartExample.createCriteria();
        criteria2.andProductIdEqualTo(cartAddBo.getProductId())
                .andUserIdEqualTo(cartAddBo.getUserId())
                .andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        if(carts.size() == 1)
        {
            Cart cart = carts.get(0);
            if(cart.getNumber() + cartAddBo.getNumber() < 0 || cart.getNumber() + cartAddBo.getNumber() > 32767)
            {
                return -1;
            }
            cart.setNumber((short) (cart.getNumber() + cartAddBo.getNumber()));
            criteria2.andIdEqualTo(cart.getId());
            cart.setId(null);
            int i = cartMapper.updateByExampleSelective(cart,cartExample);
            return i ;
        }


        Cart cart = new Cart();
        cart.setAddTime(new Date(java.lang.System.currentTimeMillis()));
        cart.setUpdateTime(new Date(java.lang.System.currentTimeMillis()));
        cart.setChecked(true);
        cart.setDeleted(false);
        cart.setUserId(cartAddBo.getUserId());
        //购物车的添加数量需要先判断一下，是不是再0-32767
        if(cartAddBo.getNumber() > 32767 || cartAddBo.getNumber() < 0)
        {
            return -1;
        }
        cart.setNumber(cartAddBo.getNumber());
        //商品信息需要查
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andIdEqualTo(cartAddBo.getGoodsId());
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);

        cart.setGoodsId(cartAddBo.getGoodsId());
        cart.setGoodsName(goods.get(0).getName());
        cart.setGoodsSn(goods.get(0).getGoodsSn());

        //商品分类信息需要查,价格需要算
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        GoodsProductExample.Criteria criteria1 = goodsProductExample.createCriteria();
        criteria1.andIdEqualTo(cartAddBo.getProductId());
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);

        cart.setProductId(cartAddBo.getProductId());
        cart.setPicUrl(goodsProducts.get(0).getUrl());
        cart.setPrice(goodsProducts.get(0).getPrice());
        cart.setSpecifications(goodsProducts.get(0).getSpecifications());

        int i = cartMapper.insertSelective(cart);

        return i;
    }

    @Override
    public WxCartListVo getCartIndex(Integer loginUserid) {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(loginUserid)
                .andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        WxCartListVo wxCartListVo = new WxCartListVo();
        wxCartListVo.setCartList(carts);

        int goodsCount = 0;
        int checkedGoodsCount = 0;
        BigDecimal goodsAmount = new BigDecimal(0);
        BigDecimal checkedgoodsAmount = new BigDecimal(0);

        for (Cart cart : carts) {
            goodsCount += cart.getNumber();
            BigDecimal price = cart.getPrice();
            price = price.multiply(new BigDecimal(cart.getNumber()));
            goodsAmount = goodsAmount.add(price);
            if (cart.getChecked())
            {
                checkedGoodsCount += cart.getNumber();
                checkedgoodsAmount = checkedgoodsAmount.add(price);
            }
        }

        CartCountInfo cartCountInfo = new CartCountInfo(checkedgoodsAmount,checkedGoodsCount,goodsAmount,goodsCount);

        wxCartListVo.setCartTotal(cartCountInfo);


        return wxCartListVo;
    }

    @Override
    public WxCartListVo CheckGoods(CheckedBo checkedBo) {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(checkedBo.getUserId())
                .andProductIdIn(checkedBo.getProductIds());

        List<Cart> carts = cartMapper.selectByExample(cartExample);
        for (Cart cart : carts) {
            if(checkedBo.getIsChecked() == 1)
            {
                cart.setChecked(true);
            }
            else
            {
                cart.setChecked(false);
            }
           CartExample cartExample1 = new CartExample();
           CartExample.Criteria criteria1 = cartExample1.createCriteria();
           criteria1.andIdEqualTo(cart.getId());
           cart.setId(null);

           cartMapper.updateByExampleSelective(cart,cartExample1);
        }

        return getCartIndex(checkedBo.getUserId());
    }

    @Override
    public void updateCart(CartUpdateBo cartUpdateBo) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andIdEqualTo(cartUpdateBo.getId());

        Cart cart = new Cart();
        cart.setNumber(cartUpdateBo.getNumber());

        cartMapper.updateByExampleSelective(cart,cartExample);
    }

    @Override
    public CheckInfoVo checkoutInfo(Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId) {

        CheckInfoVo checkInfoVo  = new CheckInfoVo();
        //不写团购
        checkInfoVo.setGrouponPrice(0);
        checkInfoVo.setGrouponRulesId(0);
        //检查地址信息
        AddressExample addressExample = new AddressExample();
        AddressExample.Criteria criteria = addressExample.createCriteria();
        criteria.andUserIdEqualTo(UserIdUtil.getUserId());
        if(addressId == 0)
        {
            criteria.andIsDefaultEqualTo(true);
        }
        else {
            criteria.andIdEqualTo(addressId);

        }
            List<Address> addresses = addressMapper.selectByExample(addressExample);
            if (addresses.size() == 0)
            {
                checkInfoVo.setCheckedAddress(null);
                checkInfoVo.setAddressId(addressId);
            }
            else
            {
                checkInfoVo.setCheckedAddress(addresses.get(0));
                checkInfoVo.setAddressId(addressId);
            }



        //检查所有选中的购物车商品
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria1 = cartExample.createCriteria();
        criteria1.andUserIdEqualTo(UserIdUtil.getUserId())
                .andCheckedEqualTo(true)
                .andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        checkInfoVo.setCheckedGoodsList(carts);

        //返回可用优惠券数量，以及计算选中优惠券后的价格
        //先计算临时总价判断能不能用优惠券
        WxCartListVo cartIndex = getCartIndex(UserIdUtil.getUserId());
        BigDecimal tempAmount = cartIndex.getCartTotal().getCheckedGoodsAmount();
        checkInfoVo.setGoodsTotalPrice(tempAmount.doubleValue());
        //查找正在用的优惠券信息，计算价格
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria3 = couponExample.createCriteria();
        criteria3.andIdEqualTo(couponId)
                .andMinLessThan(tempAmount);
        List<Coupon> coupons = couponMapper.selectByExample(couponExample);
        if(coupons.size() == 1)
        {
            Coupon coupon = coupons.get(0);
            checkInfoVo.setCouponId(coupon.getId());
            checkInfoVo.setCouponPrice(coupon.getDiscount().doubleValue());
            tempAmount = tempAmount.subtract(coupon.getDiscount());
        }
        else //如果没查到这张传进来的优惠券，则表示是有傻逼在偷,或者是没用优惠券（-1）,此时向后走，随便找一张他能用的优惠券
        {
        }
        //查找可用优惠券信息
        Coupon_UserExample coupon_userExample = new Coupon_UserExample();
        Coupon_UserExample.Criteria criteria5 = coupon_userExample.createCriteria();
        criteria5.andDeletedEqualTo(false)
                .andUserIdEqualTo(UserIdUtil.getUserId())
                .andEndTimeGreaterThan(new Date(java.lang.System.currentTimeMillis()))
                .andStartTimeLessThan(new Date(java.lang.System.currentTimeMillis()));

        List<Coupon_User> coupon_users = coupon_userMapper.selectByExample(coupon_userExample);
        List<Integer> couponids = new ArrayList<>();
        for (Coupon_User coupon_user : coupon_users) {
            couponids.add(coupon_user.getCouponId());
        }


        CouponExample couponExample1 = new CouponExample();
        CouponExample.Criteria criteria6 = couponExample1.createCriteria();


        criteria6.andIdIn(couponids).andMinLessThan(tempAmount);

        List<Coupon> coupons1 = couponMapper.selectByExample(couponExample1);


        //如果一开始没查到可用优惠券，此时随便搞一张可用的优惠券给他
        if(coupons.size() == 0)
        {
            checkInfoVo.setCouponId(coupons1.get(0).getId());
            checkInfoVo.setCouponPrice(coupons1.get(0).getDiscount().doubleValue());
        }

        List<Integer> couponids2 = new ArrayList<>();
        for (Coupon coupon : coupons1) {
            couponids2.add(coupon.getId());
        }

        criteria5.andCouponIdIn(couponids2);

        List<Coupon_User> coupon_users1 = coupon_userMapper.selectByExample(coupon_userExample);

        checkInfoVo.setAvailableCouponLength(coupon_users1.size());

        //再看是否需要运费

        SystemExample systemExample2 = new SystemExample();
        SystemExample.Criteria criteria4 = systemExample2.createCriteria();
        criteria4.andKeyNameEqualTo("cskaoyan_mall_express_freight_min");
        List<System> systems1 = systemMapper.selectByExample(systemExample2);

        if(Integer.parseInt(systems1.get(0).getKeyValue()) > tempAmount.doubleValue())
        {
            SystemExample systemExample = new SystemExample();
            SystemExample.Criteria criteria2 = systemExample.createCriteria();
            criteria2.andKeyNameEqualTo("cskaoyan_mall_express_freight_value");
            List<System> systems = systemMapper.selectByExample(systemExample);
            System system = systems.get(0);
            String freightFee = system.getKeyValue();
            checkInfoVo.setFreightPrice(Integer.parseInt(freightFee));
        }
        else
        {
            checkInfoVo.setFreightPrice(0);
        }

        tempAmount = tempAmount.add(new BigDecimal(checkInfoVo.getFreightPrice()));
        checkInfoVo.setActualPrice(tempAmount.doubleValue());
        checkInfoVo.setOrderTotalPrice(checkInfoVo.getActualPrice());

        return checkInfoVo;
    }

    @Override
    public WxCartListVo deleteCart(DeleteCartBo deleteCartBo) {

        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andProductIdIn(deleteCartBo.getProductIds())
                .andUserIdEqualTo(deleteCartBo.getUserId());
        Cart cart = new Cart();
        cart.setDeleted(true);
        cartMapper.updateByExampleSelective(cart,cartExample);

        return getCartIndex(deleteCartBo.getUserId());
    }
}
